import React, { forwardRef, useState, useImperativeHandle, useRef, useEffect } from "react";
import {
    Form, Popover, DatePicker, Input, Radio, InputNumber, Tag, Button, Space, Modal, Divider, Icon,
    message, Table, Spin, Progress, Tooltip,
    Select,
    Switch
} from '@bytedance/mona-ui';
import type { ColumnProps } from '@bytedance/mona-ui/es/components/table';
import { addCouponFun, stopAddConter } from '../couponFunc'
import GoodsTable from '../goodsTable'
import { useAppSelector } from "~store"
import moment from 'moment';
import 'moment/locale/zh-cn';
import { checkPromotionProductList } from "@Api/productApi"
import { generateRandomString } from '../../../../jinritemaiCopyGoods/copyDataFomate'

const { Option } = Select

moment.locale('zh-cn');
const { RangePicker } = DatePicker;

function Coupon(props, ref) {

    const { modowType, editConfigData, menulistData, setMenulistData, selectMunu, setAddMunStext } = props
    // console.log('menulistData', menulistData)
    const reseteStatus = {
        errLijStatus: '',
        errLijTitle: null,
        errmonTitle: null,
        errmonStatus: '',
        errzekouTitle: null,
        errzekouStatus: '',
        fanTitle: null,
        fanStatus: ''
    }
    let couConfig: any = {
        geveTimeDateConf: {
            geveTimeDate: '7',
            selectGeveTimetype: '1',
        },

        valid_period: '7',
        goodsScope: 1,

        creditConf: {
            credit: '',
            threshold: '',
            discount: '',

        },

        discountType: 1,
        total_amount: '',
        max_apply_times: 1,
        couponGoodsNum: 30,
        couponAfterText: '',



        reseteStatus,

        createBeforConf: {
            createBefor: 3,
            sendNumActivet: 0,
            sendTimeActivet: 0,
            useNum: 0
        },
        isTopActivet: true,
        MPTime: 10,
        getSelectGoods: [],
        status: 0, // 0未开时 1进行中 2完成 3失败 4取消  7 // 等待进行 6 部分商品完成设置 9部分进行中
        selectMenuConter: selectMunu || 'all',
        getTime: [moment().startOf('day'), moment().add(1, 'day').startOf('day').subtract(1, 'second')]

    }
    if (modowType !== 'add' && editConfigData) {
        console.log('editConfigData', editConfigData)
        couConfig = JSON.parse(JSON.stringify(editConfigData))
        couConfig.getTime = [moment(couConfig.getTime[0] * 1000), moment(couConfig.getTime[1] * 1000)]
    }

    const [addCouponConfig, setAddCouponConfig] = useState<any>(couConfig)
    let { goodsScope } = addCouponConfig

    const [couponTableDataAll, setCouponTableDataAll] = useState([])
    const [couponTableDataShop, setCouponTableDataShop] = useState([])
    const [couponTableDataCoup, setCouponTableDataCoup] = useState([])

    useImperativeHandle(ref, () => ({
        someMethod,
    }));
    const [couConfigForm] = Form.useForm()
    const [couInConfigForm] = Form.useForm()

    // useEffect(() => {
    //     console.log('couConfigForm', couConfigForm.getFieldsValue())

    // }, [modowType])

    type ChildMethods = {
        // 子组件暴露给父组件的方法
        getSelectGoods: () => void;
        getProdectListFunAs: () => void;
    };
    const selectGoodsdRef = useRef<ChildMethods>(null);
    const isBuyStatus = useAppSelector(
        (state) => state.jinritemaiProduct.isBuyStatus
    )
    const someMethod = async () => {
        const tableData = goodsScope === 2 ? couponTableDataAll : couponTableDataCoup
        if (!tableData || !tableData.length) {
            message.error('请先添加优惠券内容')
            return false
        }
        let addCOnter = []
        const getSelectGoods: any = selectGoodsdRef.current?.getSelectGoods()
        if (goodsScope == 1 && (!getSelectGoods || !getSelectGoods.length)) {
            message.error('请先选择商品')
            return false
        }
        tableData.forEach((item: any) => {
            const getAlltet = couInConfigForm.getFieldsValue()
            const getAlltet2 = couConfigForm.getFieldsValue()
            getAlltet.reseteStatus = reseteStatus
            getAlltet.getSelectGoods = []
            getAlltet.status = modowType === 'edit' ? addCouponConfig.status : 0
            if (selectGoodsdRef.current) {

                getAlltet.getSelectGoods = getSelectGoods
            }
            const getConter = Object.assign(getAlltet, getAlltet2)
            getConter.creditConf = {
                credit: item.credit,
                threshold: item.threshold,
                discount: item.discount
            }
            getConter.discountType = item.discountType
            getConter.total_amount = item.total_amount
            getConter.max_apply_times = item.max_apply_times
            getConter.getTime = [getConter.getTime[0].unix(), getConter.getTime[1].unix()]
            getConter.createBeforConf = item.createBeforConf
            addCOnter.push(getConter)
        })
        return addCOnter
    };

    const [addCouponList, setAddCouponList] = useState(false)

    const [couponListDataShop, setCouponListDataShop] = useState([couponListDataFater(2)])
    const [couponListDataAll, setCouponListDataAll] = useState([couponListDataFater(1)])
    const [editCouponStatus, setEditCounponStatus] = useState({
        status: false,
        index: -1
    })
    const [showAddCouponStuats, setShowAddCouponStuats] = useState((_ => {
        const dlyfundata = localStorage.getItem('dlyfundataAddun')
        const infoDate = {
            addconpon: true
        }
        setTimeout(_ => {
            localStorage.setItem('dlyfundataAddun', JSON.stringify(infoDate))
        }, 200)
        try {
            const getJson = JSON.parse(dlyfundata)
            if (getJson.addconpon) return false
        } catch (error) {
            return true
        }
        return true
    })())
    interface ColumnPropsType {
        index: number;
        name: string;
        createBeforConf: any
    }
    const couponTitle: ColumnProps<ColumnPropsType>[] = [
        {
            title: 'ID',
            key: '5',
            // dataIndex: 'ID',
            align: "center",
            render: (_, record, index) => {
                return ++index
            },
        },
        {
            title: '券内容',
            key: '0',
            dataIndex: 'couponName',
            align: "center",
        },
        {
            title: '力度',
            key: '1',
            dataIndex: 'meter',
            align: "center",
        },
        {
            title: '发行量',
            key: '2',
            dataIndex: 'total_amount',
            align: "center",
        },
        {
            title: '每人领',
            key: '3',
            dataIndex: 'max_apply_times',
            align: "center",
        },
        {
            title: '创建时机',
            // dataIndex: 'createBefor',
            align: "center",
            width: 200,
            render: (text, record, index) => {
                if (!record.createBeforConf) return null
                return record.createBeforConf.createBefor === 1 ?
                    `领取时间结束前${record.createBeforConf.sendTimeActivet}分钟` :
                    record.createBeforConf.createBefor === 2 ? `优惠券领取剩余${record.createBeforConf.sendNumActivet}张` : record.createBeforConf.createBefor === 4 ? `使用${record.createBeforConf.useNum}张` :
                        `时间结束前${record.createBeforConf.sendTimeActivet}分钟或领取剩余${record.createBeforConf.sendNumActivet}张${record.createBeforConf.useNum ? `或使用${record.createBeforConf.useNum}张` : ''}`
            },
        },
        {
            title: '操作',
            key: '4',
            dataIndex: 'birth',
            align: "center",
            render: (_, record, index) => {
                return (
                    <Space>
                        <Icon
                            type="EditIcon" style={{
                                fontSize: 16,
                                color: '#2970FF',
                                cursor: 'pointer'
                            }}
                            onClick={() => {
                                console.log('编辑')
                                setEditCounponStatus({
                                    status: true,
                                    index
                                })
                                setAddCouponList(true)
                                // let setTabData = goodsScope === 1 ? couponTableDataShop : couponTableDataAll
                                // let setTabFun = goodsScope === 1 ? setCouponTableDataShop : setCouponTableDataAll
                                // setTabData.splice(index, 1)
                                // setTabFun([...setTabData])
                            }}
                        ></Icon>
                        <Icon
                            type="DeleteIcon" style={{
                                fontSize: 16,
                                color: 'red',
                                cursor: 'pointer'
                            }}
                            onClick={() => {
                                let setTabData = goodsScope === 1 ? couponTableDataCoup : couponTableDataAll
                                let setTabFun = goodsScope === 1 ? setCouponTableDataCoup : setCouponTableDataAll
                                setTabData.splice(index, 1)
                                setTabFun([...setTabData])
                            }}
                        ></Icon>
                    </Space>

                );
            },
        }]

    function couponListDataFater(params) {
        return {
            favoured_type: params === 1 ? 22 : 42,
            discountType: 3,
            discount: '',
            credit: '',
            threshold: '',
            total_amount: '',
            max_apply_times: 1,
            key: new Date().getTime(),
            reseteStatus: {
                errLijStatus: '',
                errLijTitle: null,
                errmonStatus: '',
                errmonTitle: null,
                errzekouStatus: '',
                errzekouTitle: null,
                fanStatus: '',
                fanTitle: null

            },
            createBeforConf: {
                createBefor: 2,
                useNum: 0,
                sendNumActivet: 0,
                sendTimeActivet: 0

            }

        }

    }

    const [menuConterTuter, setMenuConterTuter] = useState('')
    const [focusState, setFocusState] = useState<'start' | 'end' | null>('start');
    function disabledDate(current) {
        // console.log('addCouponConfig.getTime', addCouponConfig.getTime)
        // console.log('focusState', addCouponConfig.getTime?.[0])
        if (focusState === 'start') {
            return (current && (current < moment().subtract(1, 'days') || current > moment().add(1, 'years')));
        }
        if (focusState === 'end') {
            return (current && (current < moment(addCouponConfig.getTime?.[0]).subtract(1, 'days') || current > moment(addCouponConfig.getTime?.[0]).add(1, 'years')));
        }
    }

    return (<div>
        <h3>软件在开始设置时会自动跳过不可参加活动的商品</h3>
        {/* 加入一个没有被设置上的商品列表 */}
        <div className="shger">

            <Form
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 24 }}
                layout="horizontal"
                name="couponConfig"
                initialValues={addCouponConfig}
                style={{
                    flex: 1
                }}
                form={couInConfigForm}
            >
                <Form.Item
                    noStyle
                >
                    <h3>优惠券设置</h3>
                </Form.Item>
                {/* <Form.Item
                    // name="geveTimeDate"
                    label="优惠券设置时间"
                    tooltip="活动开始后的时间段，从活动开始计算"
                    rules={[
                        {
                            required: true,
                            message: '优惠券设置时间必填',
                        },
                    ]}
                >
                    <Input.Group compact>
                        <Form.Item noStyle name={['geveTimeDateConf', 'geveTimeDate']}>
                            <Input width={120} defaultValue={addCouponConfig.geveTimeDateConf.geveTimeDate} placeholder="请输入数字"
                                onChange={(e) => {
                                    // setAddCouponConfig({ ...addCouponConfig, geveTimeDate: e.target.value })
                                }}
                            ></Input>
                        </Form.Item>
                        <Form.Item noStyle name={['geveTimeDateConf', 'selectGeveTimetype']}>

                            <Select defaultValue={addCouponConfig.geveTimeDateConf.selectGeveTimetype} onChange={(e) => {
                                // setAddCouponConfig({ ...addCouponConfig, selectGeveTimetype: e })
                            }}>
                                <Select.Option value="0">小时</Select.Option>
                                <Select.Option value="1">天</Select.Option>
                            </Select>
                        </Form.Item>

                    </Input.Group>
                </Form.Item> */}

                <Form.Item
                    name="getTime"
                    label="领取时间"
                    rules={[
                        {
                            required: true,
                            message: '领取时间必填',
                        },
                    ]}
                >
                    <RangePicker
                        ranges={{
                            '1天内': [moment(), moment().add(1, 'days')],
                            '今晚0点一天内': [moment().add(1, 'day').startOf('day'), moment().add(2, 'day').startOf('day').subtract(1, 'second')],
                            '3天内': [moment(), moment().add(3, 'days')],
                            '今晚0点三天内': [moment().add(1, 'day').startOf('day'), moment().add(4, 'day').startOf('day').subtract(1, 'second')],
                            '一周内': [moment(), moment().add(7, 'days')],
                            '今晚0点一周内': [moment().add(1, 'day').startOf('day'), moment().add(8, 'day').startOf('day').subtract(1, 'second')],
                        }}
                        // timePickerProps={{
                        //     format: 'HH:mm:ss',
                        //   }}
                        showTime
                        disabledDate={disabledDate}
                        // disabledTime={disabledRangeTime}
                        format="YYYY-MM-DD HH:mm:ss"
                        onFocus={(_, { range }) => {
                            console.log('onFocus2', range);
                            setFocusState(range);
                        }}
                        onOpenChange={open => {
                            if (!open) {
                                setFocusState('start');
                            }
                        }}
                    // onCalendarChange={(e: any) => {
                    //     addCouponConfig.getTime = e
                    //     setAddCouponConfig({ ...addCouponConfig })
                    // }}
                    // onChange={(e) => {
                    //     console.log('e', e[0].unix(), e[1].unix())
                    //     addCouponConfig.getTime = e
                    //     if (e) {
                    //         addCouponConfig.start_apply_time = e[0].unix()
                    //         addCouponConfig.end_apply_time = e[1].unix()
                    //     } else {
                    //         addCouponConfig.start_apply_time = ''
                    //         addCouponConfig.end_apply_time = ''
                    //     }

                    //     setAddCouponConfig({ ...addCouponConfig })
                    // }}
                    ></RangePicker>
                </Form.Item>




                <Form.Item
                    name="valid_period"
                    label="券使用时间"
                    rules={[
                        {
                            required: true,
                            message: '券使用时间必选',
                        },
                    ]}
                >
                    <InputNumber
                        placeholder="请输入数字"
                        min={1}
                        max={180}
                        unit='天内可使用'
                        defaultValue={addCouponConfig.valid_period}
                        onChange={(e: any) => {
                            // addCouponConfig.valid_period = e
                            // setAddCouponConfig({ ...addCouponConfig })
                        }}
                    />
                </Form.Item>

                <Form.Item
                    name='goodsScope'
                    label="商品范围">
                    <Radio.Group defaultValue={addCouponConfig.goodsScope} onChange={(e: any) => {
                        addCouponConfig.goodsScope = e.target.value
                        setAddCouponConfig({ ...addCouponConfig })
                    }}>
                        <Radio value={2}>全店商品（店铺券）</Radio>
                        <Radio value={1}>指定商品（商品券）</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item
                    name="couponList"
                    label="优惠券">
                    <Space direction="vertical" style={{
                        width: '100%'
                    }}>
                        <Button type="primary" size="mini" onClick={() => {
                            setAddCouponList(true)
                        }}>添加优惠券</Button>
                        {(() => {
                            // return <Table></Table>
                            const tableData = goodsScope === 2 ? couponTableDataAll : couponTableDataCoup
                            return <Table
                                locale={{
                                    emptyText: <div>数据为空，请前往<Button type="link" onClick={() => {
                                        setAddCouponList(true)
                                    }}>添加优惠券</Button></div>
                                }}
                                rowKey="index"
                                columns={couponTitle}
                                dataSource={tableData}
                                bordered
                                pagination={{ hideOnSinglePage: true }}
                            />
                        })()}
                    </Space>
                </Form.Item>




                {/* <Form.Item
                    name="discountType"
                    label="优惠类型"

                >
                    <Radio.Group defaultValue={addCouponConfig.discountType} onChange={(e: any) => {
                        setAddCouponConfig({ ...addCouponConfig, discountType: e.target.value })
                    }}>
                        <Radio value={1}>立减</Radio>
                        <Radio value={2}>满减</Radio>
                        <Radio value={3}>折扣</Radio>
                    </Radio.Group>
                </Form.Item>

                {addCouponConfig.discountType == 1 &&
                    <Form.Item
                        name={['creditConf', 'credit']}
                        label="立减面额"
                        // help={addCouponConfig.reseteStatus.errLijTitle}
                        // validateStatus={addCouponConfig.reseteStatus.errLijStatus}
                        rules={[
                            {
                                required: true,
                                message: '请输入立减面额',
                            },
                        ]}>
                        <InputNumber
                            placeholder="请输入数字"
                            min={1}
                            max={1000}
                            prefix="￥"
                            defaultValue={addCouponConfig.creditConf.credit}
                            onChange={(e: any) => {
                                // // addCouponConfig.credit = e
                                // if (!addCouponConfig.creditConf.credit) {
                                //     addCouponConfig.reseteStatus.errLijStatus = 'error'
                                //     addCouponConfig.reseteStatus.errLijTitle = '立减金额不能为空'
                                // } else {
                                //     addCouponConfig.reseteStatus.errLijStatus = ''
                                //     addCouponConfig.reseteStatus.errLijTitle = null
                                // }
                                // setAddCouponConfig({ ...addCouponConfig })
                            }}
                        />
                    </Form.Item>
                }

                {addCouponConfig.discountType == 2 &&
                    <Form.Item
                        help={addCouponConfig.reseteStatus.errmonTitle}
                        validateStatus={addCouponConfig.reseteStatus.errmonStatus}
                        // name="threshold"
                        label="满减面额" >
                        <Space>
                            满
                            <Form.Item noStyle name={['creditConf', 'threshold']} rules={[
                                {
                                    required: true,
                                    message: '请输入满减面额',
                                },
                            ]}>
                                <InputNumber
                                    placeholder="请输入数字"
                                    min={1}
                                    max={99999}
                                    prefix="￥"
                                    defaultValue={addCouponConfig.creditConf.threshold}
                                    style={{
                                        width: 32
                                    }}
                                    onChange={(e: any) => {
                                        // item.threshold = e
                                        // setFunData([...forList])
                                        // setAddCouponConfig({ ...addCouponConfig, threshold: e })
                                    }}
                                />
                            </Form.Item>
                            减

                            <Form.Item noStyle name={['creditConf', 'credit']} rules={[
                                {
                                    required: true,
                                    message: '请输入满减面额',
                                },
                            ]}>
                                <InputNumber
                                    placeholder="请输入数字"
                                    min={1}
                                    max={99999}
                                    prefix="￥"
                                    value={addCouponConfig.creditConf.credit}
                                    style={{
                                        width: 32
                                    }}
                                    onChange={(e: any) => {
                                        // item.credit = e
                                        // setFunData([...forList])
                                        // setAddCouponConfig({ ...addCouponConfig, credit: e })
                                    }}
                                />
                            </Form.Item>
                            元

                        </Space>
                    </Form.Item>
                }
                {addCouponConfig.discountType == 3 &&
                    <Form.Item
                        name={['creditConf', "discount"]}
                        // help={addCouponConfig.reseteStatus.errzekouTitle}
                        // validateStatus={addCouponConfig.reseteStatus.errzekouStatus}
                        rules={[
                            {
                                required: true,
                                message: '请输入折扣',
                            },
                        ]}
                        label="折扣">
                        <InputNumber
                            placeholder="请输入折扣 2 - 9.9折"
                            min={2}
                            max={9.9}
                            step={1}
                            unit='折'
                            defaultValue={addCouponConfig.creditConf.discount}
                            onChange={(e: any) => {
                                // addCouponConfig.discount = e
                                if (!addCouponConfig.creditConf.discount) {
                                    addCouponConfig.reseteStatus.errzekouStatus = 'error'
                                    addCouponConfig.reseteStatus.errzekouTitle = '折扣不能不为空'
                                } else {
                                    addCouponConfig.reseteStatus.errzekouStatus = ''
                                    addCouponConfig.reseteStatus.errzekouTitle = null
                                }
                                // setFunData([...forList])
                                setAddCouponConfig({ ...addCouponConfig })
                            }}
                        />
                    </Form.Item>}
                <Form.Item
                    name="total_amount"
                    label="发放量"
                    // help={addCouponConfig.reseteStatus.fanTitle}
                    // validateStatus={addCouponConfig.reseteStatus.fanStatus}
                    rules={[
                        {
                            required: true,
                            message: '请输入发放量',
                        },
                    ]}>
                    <InputNumber
                        placeholder="请输入数字"
                        min={1}
                        max={1000000}
                        unit='张'
                        defaultValue={addCouponConfig.total_amount}
                        onChange={(e: any) => {
                            // addCouponConfig.total_amount = e
                            // if (!addCouponConfig.total_amount) {
                            //     addCouponConfig.reseteStatus.fanStatus = 'error'
                            //     addCouponConfig.reseteStatus.fanTitle = '发放数量不能为空'
                            // } else {
                            //     addCouponConfig.reseteStatus.fanStatus = ''
                            //     addCouponConfig.reseteStatus.fanTitle = null
                            // }
                            // setAddCouponConfig({ ...addCouponConfig })
                        }}
                    />
                </Form.Item>
                <Form.Item name="max_apply_times" label="每人领">
                    <Radio.Group defaultValue={addCouponConfig.max_apply_times} onChange={(e: any) => {
                        setAddCouponConfig({ ...addCouponConfig, max_apply_times: e.target.value })
                    }}>
                        <Radio value={1}>1张</Radio>
                        <Radio value={2}>2张</Radio>
                        <Radio value={3}>3张</Radio>
                        <Radio value={4}>4张</Radio>
                        <Radio value={5}>5张</Radio>
                    </Radio.Group>
                </Form.Item> */}
                {goodsScope === 1 && (
                    <>
                        <Form.Item
                            name="couponGoodsNum"
                            label="每个券活动商品数"
                            rules={[
                                {
                                    required: true,
                                    message: '每个券活动商品数必填',
                                },
                            ]}
                        >
                            <InputNumber
                                placeholder="请输入数字"
                                min={1}
                                max={200}
                                unit='个'
                                defaultValue={addCouponConfig.couponGoodsNum}
                                onChange={(e: any) => {
                                    addCouponConfig.couponGoodsNum = e
                                    setAddCouponConfig({ ...addCouponConfig })
                                }}
                            />
                        </Form.Item>
                    </>
                )}
                <Form.Item
                    name="couponAfterText"
                    label="优惠券前缀">
                    <Input placeholder="可添加优惠券前缀名称" defaultValue={addCouponConfig.couponAfterText} onChange={(e) => {
                        addCouponConfig.couponAfterText = e.target.value.slice(0, 5)
                        setAddCouponConfig({ ...addCouponConfig })
                    }} maxLength={5} style={{
                        width: 250
                    }}></Input>
                </Form.Item>
                <Form.Item
                    name='selectMenuConter'
                    label="任务分组"
                >
                    <Select
                        style={{ width: 240 }}
                        placeholder="清选择任务分组"
                        dropdownRender={menu => (
                            <div>
                                {menu}
                                <Divider style={{ margin: '4px 0' }} />
                                <Space style={{
                                    width: '100%',
                                    padding: '0px 5px',
                                    justifyContent: "space-between"
                                }}>
                                    <Input style={{ flex: 'auto' }} value={menuConterTuter} size="small" placeholder="请输入分组名称" onChange={(e) => {
                                        setMenuConterTuter(e.target.value)
                                    }} />
                                    <Button type="link" onClick={() => {
                                        if (!menuConterTuter) {
                                            message.error('请输入分组名称')
                                            return
                                        }
                                        setMenulistData && setMenulistData([...menulistData, {
                                            name: menuConterTuter,
                                            key: generateRandomString(8) + String(Date.now()).substr(5) + String(Math.random()).substr(2, 4)
                                        }])
                                        setMenuConterTuter('')
                                    }}>添加</Button>
                                </Space>
                            </div>
                        )}
                        onChange={(e) => {

                            setAddMunStext(e)
                        }}
                    >
                        {menulistData.map(item => (
                            <Option key={item.key} value={item.key}>{item.name}</Option>
                        ))}
                    </Select>
                    {/* <Select
                        // value={addCouponConfig.createBefor}
                        onChange={(e) => {
                            addCouponConfig.createBeforConf.createBefor = e
                            setAddCouponConfig({ ...addCouponConfig })
                        }}
                    >
                        <Select.Option value={1}>领取时间结束前</Select.Option>
                        <Select.Option value={2}>优惠券领取剩余</Select.Option>
                        <Select.Option value={3}>时间结束前或领取剩余</Select.Option>
                    </Select> */}
                </Form.Item>
            </Form>

        </div>

        {goodsScope === 1 && <Divider />}
        {goodsScope === 1 && <GoodsTable ref={selectGoodsdRef} addCouponConfig={addCouponConfig} couponTableDataShop={couponTableDataShop} autoStatus={true} selectGoodsList={addCouponConfig.getSelectGoods}></GoodsTable>}
        {(() => {
            let forList = goodsScope === 2 ? couponListDataAll : couponListDataShop
            const setFunData = goodsScope === 2 ? setCouponListDataAll : setCouponListDataShop
            return <Modal
                visible={addCouponList}
                title={editCouponStatus.status ? '编辑优惠券' : `添加优惠券: 已添加 ${forList.length} 张`} // : 已添加' + forList.length + '张'
                okText=" 确定"
                cancelText=" 取消"
                width={1100}
                destroyOnClose
                onCancel={() => {
                    setEditCounponStatus({
                        status: false,
                        index: -1
                    })
                    setAddCouponList(false)
                }}
                footer={
                    <div className="bote" style={{
                        display: 'flex',
                        justifyContent: 'space-between'
                    }}>
                        <div className="leter">
                            {!editCouponStatus.status &&
                                <Popover
                                    content={(
                                        <Space direction="vertical" >
                                            <div>这里可以添加多张优惠券</div>
                                            <div className="moter" style={{
                                                width: '100%',
                                                display: 'flex',
                                                justifyContent: 'flex-end'
                                            }}>
                                                <Button size="mini" type="primary" onClick={() => {
                                                    setShowAddCouponStuats(false)
                                                }}>知道了</Button>
                                            </div>
                                        </Space>
                                    )}
                                    visible={showAddCouponStuats}>

                                    <Button size="mini" onClick={() => {
                                        forList.push(couponListDataFater(goodsScope))
                                        setFunData([...forList])
                                    }} icon={
                                        <Icon type="AddIcon"></Icon>}>
                                        新增优惠券
                                    </Button>

                                </Popover>
                            }
                        </div>
                        <div className="rngdtrr">
                            <Space>
                                <Button type="primary" size="mini" onClick={async () => {
                                    // 检查添加项
                                    let addkey = false
                                    // 这里请求活动是否配置情况


                                    forList.forEach(item => {
                                        item.reseteStatus = {
                                            errLijStatus: '',
                                            errLijTitle: null,
                                            errmonStatus: '',
                                            errmonTitle: null,
                                            errzekouStatus: '',
                                            errzekouTitle: null,
                                            fanStatus: '',
                                            fanTitle: null
                                        }
                                    })
                                    forList.forEach(async (item: any, index) => {
                                        switch (item.discountType) {
                                            case 1:
                                                if (!item.credit) {
                                                    item.reseteStatus.errLijStatus = 'error'
                                                    item.reseteStatus.errLijTitle = '立减金额不能为空'
                                                    addkey = true
                                                    // throw new Error('立减金额不能为空')
                                                }
                                                break;
                                            case 2:
                                                if (!item.threshold || !item.credit) {
                                                    item.reseteStatus.errmonStatus = 'error'
                                                    item.reseteStatus.errmonTitle = '满减金额不能为空'
                                                    addkey = true
                                                    return
                                                    // throw new Error('立减金额不能为空')
                                                }
                                                if (item.credit >= item.threshold) {
                                                    item.reseteStatus.errmonStatus = 'error'
                                                    item.reseteStatus.errmonTitle = '满额必须大于减额'
                                                    addkey = true
                                                    return
                                                }
                                                if ((item.credit / item.threshold) < 0.02) {
                                                    const mincater = Math.floor(item.threshold * 0.02)
                                                    const maxcater = Math.floor(item.threshold * 0.8)
                                                    item.reseteStatus.errmonStatus = 'error'
                                                    item.reseteStatus.errmonTitle = `优惠力度过小，需大于2%减额可填写的区间为¥${mincater}-¥${maxcater}`
                                                    addkey = true
                                                    return
                                                }
                                                if ((item.credit / item.threshold) > 0.8) {
                                                    const mincater = Math.floor(item.threshold * 0.02)
                                                    const maxcater = Math.floor(item.threshold * 0.8)
                                                    item.reseteStatus.errmonStatus = 'error'
                                                    item.reseteStatus.errmonTitle = `优惠力度过大，需小于80%减额可填写的区间为¥${mincater}-¥${maxcater}`
                                                    addkey = true
                                                    return
                                                }

                                                break;
                                            case 3:
                                                if (!item.discount) {
                                                    item.reseteStatus.errzekouStatus = 'error'
                                                    item.reseteStatus.errzekouTitle = '折扣不能不为空'
                                                    addkey = true
                                                }
                                                break;
                                            default:
                                                break;
                                        }
                                        if (!item.total_amount) {
                                            item.reseteStatus.fanStatus = 'error'
                                            item.reseteStatus.fanTitle = '发放数量不能为空'
                                            addkey = true

                                        }
                                    })
                                    if (addkey) {
                                        setFunData([...forList])
                                        message.error('请检查必填项')
                                        return
                                    }
                                    // const getItemListeItemOne: any = forList[0]
                                    // let getTimetype
                                    // if (getItemListeItemOne.discountType == 1) {
                                    //     getTimetype = {
                                    //         "activity_tool_discount_type": 1,
                                    //         "credit": Number((getItemListeItemOne.credit * 100).toFixed(0)),
                                    //         "participate_type": 1,
                                    //         "activity_tool_type": 7,
                                    //         "validate_type": 2,
                                    //         "support_type": 1,
                                    //         // "start_time": start_apply_time,
                                    //         // "end_time": end_apply_time
                                    //     }
                                    // }

                                    // if (getItemListeItemOne.discountType == 2) {
                                    //     getTimetype = {
                                    //         "activity_tool_discount_type": 3,
                                    //         "threshold":Number( (getItemListeItemOne.threshold * 100).toFixed(0)),
                                    //         "credit": Number((getItemListeItemOne.credit * 100).toFixed(0)),
                                    //         "participate_type": 1,
                                    //         "activity_tool_type": 7,
                                    //         "validate_type": 2,
                                    //         "support_type": 1,
                                    //         // "start_time": start_apply_time,
                                    //         // "end_time": end_apply_time
                                    //     }
                                    // }
                                    // if (getItemListeItemOne.discountType == 3) {
                                    //     getTimetype = {
                                    //         "activity_tool_discount_type": 4,
                                    //         "discount": Number((getItemListeItemOne.discount * 10).toFixed(0)),
                                    //         "participate_type": 1,
                                    //         "activity_tool_type": 7,
                                    //         "validate_type": 2,
                                    //         "support_type": 1,
                                    //         // "start_time": start_apply_time,
                                    //         // "end_time": end_apply_time
                                    //     }
                                    // }
                                    // const getAtserNow: any = await checkPromotionProductList(getTimetype)
                                    // if (!getAtserNow.code) {
                                    //     if (!getAtserNow.data.activity_check_info.check_pass) {
                                    //         addkey = true
                                    //         if (getItemListeItemOne.discountType == 1) {
                                    //             getItemListeItemOne.reseteStatus.errLijStatus = 'error'
                                    //             getItemListeItemOne.reseteStatus.errLijTitle = getAtserNow.data.activity_check_info.reject_reason
                                    //         }
                                    //         if (getItemListeItemOne.discountType == 2) {
                                    //             getItemListeItemOne.reseteStatus.errmonStatus = 'error'
                                    //             getItemListeItemOne.reseteStatus.errmonTitle = getAtserNow.data.activity_check_info.reject_reason
                                    //         }
                                    //         if (getItemListeItemOne.discountType == 3) {
                                    //             getItemListeItemOne.reseteStatus.errzekouStatus = 'error'
                                    //             getItemListeItemOne.reseteStatus.errzekouTitle = getAtserNow.data.activity_check_info.reject_reason
                                    //         }
                                    //         setFunData([...forList])
                                    //         message.error('请检查填写是否符合最新优惠券规则！！！')
                                    //         return
                                    //     }
                                    // }
                                    // console.log('getAtserNow检查结果', getAtserNow)

                                    let setTibleData = goodsScope === 2 ? JSON.parse(JSON.stringify(couponListDataAll)) : JSON.parse(JSON.stringify(couponListDataShop))
                                    const setTableFun: any = goodsScope === 2 ? setCouponTableDataAll : setCouponTableDataCoup
                                    setTibleData = setTibleData.map((element, index) => {
                                        // element.index = index
                                        const setTabData = {
                                            index,
                                            couponName: `${goodsScope === 2 ? '全店' : '商品'} - ${element.discountType === 1 ? '立减' : element.discountType === 2 ? '满减' : '折扣'}`,
                                            meter: (() => {
                                                let meterText = ''
                                                switch (element.discountType) {
                                                    case 1:
                                                        meterText = `立减 ${element.credit}`
                                                        break;
                                                    case 2:
                                                        meterText = `满 ${element.threshold} 减 ${element.credit}`
                                                        break;
                                                    case 3:
                                                        meterText = `打 ${element.discount} 折`
                                                        break;
                                                    default:
                                                        break;
                                                }
                                                return meterText
                                            })()
                                        }
                                        const addData = Object.assign(element, setTabData)
                                        return addData
                                    });
                                    console.log('setTibleData', setTibleData)
                                    setTableFun([...setTibleData])
                                    setAddCouponList(false)
                                    setEditCounponStatus({
                                        status: false,
                                        index: -1
                                    })
                                }}>添加</Button>
                                <Button size="mini" onClick={() => {
                                    setAddCouponList(false)
                                    setEditCounponStatus({
                                        status: false,
                                        index: -1
                                    })
                                }}>取消</Button>
                            </Space>
                        </div>
                    </div>
                }>
                {forList.map((item: any, index) => {
                    let { threshold, credit, discountType, reseteStatus } = item
                    if (editCouponStatus.status && editCouponStatus.index != index) {
                        return null
                    }
                    return (<div key={item.key}>
                        {/* <Tag bordered type="default">
                            优惠券：{index + 1}
                        </Tag> */}
                        {!editCouponStatus.status && <Tag bordered type="default">
                            优惠券：{index + 1}
                        </Tag>}
                        <Space align="center" style={{
                            width: '100%'
                        }}>
                            <Form
                                labelCol={{ span: 4 }}
                                wrapperCol={{ span: 19 }}
                                layout="horizontal"
                                name="couponList"
                                initialValues={item}
                                key={index}
                                style={{
                                    width: '510px'
                                }}
                            >
                                <Form.Item
                                    name="discountType"
                                    label={goodsScope === 2 ? "全店通用" : "商品优惠券"}

                                >
                                    <Radio.Group onChange={(e: any) => {
                                        item.discountType = e.target.value
                                        setFunData([...forList])
                                    }}>
                                        <Radio value={1}>立减</Radio>
                                        <Radio value={2}>满减</Radio>
                                        <Radio value={3}>折扣</Radio>
                                    </Radio.Group>
                                </Form.Item>

                                {discountType === 1 &&
                                    <Form.Item
                                        name="credit"
                                        label="立减面额"
                                        help={reseteStatus.errLijTitle}
                                        validateStatus={reseteStatus.errLijStatus}
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入立减面额',
                                            },
                                        ]}>
                                        <InputNumber
                                            placeholder="请输入数字"
                                            min={1}
                                            max={1000}
                                            prefix="￥"
                                            onChange={(e: any) => {
                                                item.credit = e
                                                if (!item.credit) {
                                                    item.reseteStatus.errLijStatus = 'error'
                                                    item.reseteStatus.errLijTitle = '立减金额不能为空'
                                                } else {
                                                    item.reseteStatus.errLijStatus = ''
                                                    item.reseteStatus.errLijTitle = null
                                                }
                                                setFunData([...forList])
                                            }}
                                        />
                                    </Form.Item>
                                }

                                {discountType === 2 &&
                                    <Form.Item
                                        help={reseteStatus.errmonTitle}
                                        validateStatus={reseteStatus.errmonStatus}
                                        label="满减面额" >
                                        <Space>
                                            满
                                            <InputNumber
                                                placeholder="请输入数字"
                                                min={1}
                                                max={99999}
                                                prefix="￥"
                                                defaultValue={threshold}
                                                style={{
                                                    width: 32
                                                }}
                                                onChange={(e: any) => {
                                                    item.threshold = e
                                                    setFunData([...forList])
                                                }}
                                            />
                                            减
                                            <InputNumber
                                                placeholder="请输入数字"
                                                min={1}
                                                max={99999}
                                                prefix="￥"
                                                defaultValue={credit}
                                                style={{
                                                    width: 32
                                                }}
                                                onChange={(e: any) => {
                                                    item.credit = e
                                                    setFunData([...forList])
                                                }}
                                            />
                                            元
                                        </Space>
                                    </Form.Item>
                                }
                                {discountType === 3 &&
                                    <Form.Item
                                        name="discount"
                                        help={reseteStatus.errzekouTitle}
                                        validateStatus={reseteStatus.errzekouStatus}
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入折扣',
                                            },
                                        ]}
                                        label="折扣">
                                        <InputNumber
                                            placeholder="请输入折扣 2 - 9.9折"
                                            min={2}
                                            max={9.9}
                                            step={1}
                                            unit='折'
                                            onChange={(e: any) => {
                                                item.discount = e
                                                if (!item.discount) {
                                                    item.reseteStatus.errzekouStatus = 'error'
                                                    item.reseteStatus.errzekouTitle = '折扣不能不为空'
                                                } else {
                                                    item.reseteStatus.errzekouStatus = ''
                                                    item.reseteStatus.errzekouTitle = null
                                                }
                                                setFunData([...forList])
                                            }}
                                        />
                                    </Form.Item>}
                                <Form.Item
                                    name="total_amount"
                                    label="发放量"
                                    help={reseteStatus.fanTitle}
                                    validateStatus={reseteStatus.fanStatus}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入发放量',
                                        },
                                    ]}>
                                    <InputNumber
                                        placeholder="请输入数字"
                                        min={1}
                                        max={1000000}
                                        unit='张'
                                        onChange={(e: any) => {
                                            item.total_amount = e
                                            if (!item.total_amount) {
                                                item.reseteStatus.fanStatus = 'error'
                                                item.reseteStatus.fanTitle = '发放数量不能为空'
                                            } else {
                                                item.reseteStatus.fanStatus = ''
                                                item.reseteStatus.fanTitle = null
                                                item.createBeforConf.useNum = e
                                            }

                                            setFunData([...forList])
                                        }}
                                    />
                                </Form.Item>
                                <Form.Item name="max_apply_times" label="每人领">
                                    <Radio.Group onChange={(e: any) => {
                                        item.max_apply_times = e.target.value
                                        setFunData([...forList])
                                    }}>
                                        <Radio value={1}>1张</Radio>
                                        <Radio value={2}>2张</Radio>
                                        <Radio value={3}>3张</Radio>
                                        <Radio value={4}>4张</Radio>
                                        <Radio value={5}>5张</Radio>
                                    </Radio.Group>
                                </Form.Item>

                            </Form>
                            <Form
                                labelCol={{ span: 4 }}
                                wrapperCol={{ span: 19 }}
                                layout="horizontal"
                                name="couponList"
                                initialValues={item}
                                key={index}
                                style={{
                                    width: '510px'
                                }}
                            >
                                <Form.Item noStyle >
                                    <div className="coes" style={{
                                        color: '#565960',
                                        fontSize: '12px',
                                        lineHeight: '20px',
                                        fontWeight: 'bold',
                                        textAlign: 'left',
                                        width: '100%',
                                        paddingLeft: '10px',
                                        paddingRight: '10px',
                                        paddingTop: '10px',
                                        paddingBottom: '10px',
                                        backgroundColor: '#F5F5F533',
                                        borderRadius: '5px',
                                        marginBottom: '10px',
                                    }}>
                                        自动的任务将根据 生效中对应商品的优惠券 结合以下的条件进行判断创建，请根据实际情况设置
                                    </div>
                                </Form.Item>
                                <Form.Item label="监控条件" name={['createBeforConf', 'createBefor']} rules={[
                                    {
                                        required: true,
                                        message: '创建时机必填',
                                    },
                                ]}>
                                    <Select
                                        // value={addCouponConfig.createBefor}
                                        onChange={(e) => {
                                            // addCouponConfig.createBeforConf.createBefor = e
                                            // setAddCouponConfig({ ...addCouponConfig })
                                            item.createBeforConf.createBefor = e
                                            setFunData([...forList])
                                        }}
                                        style={{
                                            width: '250px'
                                        }}
                                    >
                                        <Select.Option value={1}>领取时间结束前</Select.Option>
                                        <Select.Option value={2}>优惠券领取剩余</Select.Option>
                                        <Select.Option value={4}>优惠券使用量</Select.Option>
                                        <Select.Option value={3}>时间结束前或领取剩余或使用量</Select.Option>
                                    </Select>
                                </Form.Item>
                                {(item.createBeforConf.createBefor == 4 || item.createBeforConf.createBefor == 3) &&
                                    <Form.Item label="使用量" validateStatus="validating">
                                        {/* help="任务将监听生效中的优惠券的使用量情况进行创建" */}

                                        <InputNumber unit='张' min={0}
                                            // defaultValue={item.createBeforConf.useNum}
                                            value={item.createBeforConf.useNum}
                                            width={200}
                                            placeholder='请输入数字'
                                            onChange={(e) => {
                                                item.createBeforConf.useNum = e
                                                setFunData([...forList])
                                            }}
                                        ></InputNumber>

                                    </Form.Item>
                                }
                                {(item.createBeforConf.createBefor == 2 || item.createBeforConf.createBefor == 3) && <Form.Item label="领取剩余" name={['createBeforConf', 'sendNumActivet']}>
                                    {/* help="任务将监听生效中的优惠券的领取剩余量进行创建" */}
                                    <InputNumber unit='张' min={0}
                                        // defaultValue={item.createBeforConf.sendNumActivet}
                                        width={200}
                                        placeholder='请输入数字'
                                        onChange={(e) => {
                                            item.createBeforConf.sendNumActivet = e
                                            setFunData([...forList])
                                        }}
                                    ></InputNumber>


                                </Form.Item>}
                                {(item.createBeforConf.createBefor == 1 || item.createBeforConf.createBefor == 3) && <Form.Item label="时间结束前" name={['createBeforConf', 'sendTimeActivet']}>
                                    {/* help="任务将监听生效中的优惠券的剩余时间进行创建" */}
                                    <InputNumber unit='分钟' min={0}
                                        // defaultValue={item.createBeforConf.sendTimeActivet}
                                        width={200}
                                        max={20} placeholder="请输入数字 0~20"
                                        onChange={(e) => {
                                            item.createBeforConf.sendTimeActivet = e
                                            setFunData([...forList])
                                        }}
                                    ></InputNumber>

                                </Form.Item>}
                            </Form>


                            {!editCouponStatus.status && <Icon
                                type="DeleteIcon" style={{
                                    fontSize: 16,
                                    color: 'red',
                                    cursor: 'pointer'
                                }}
                                onClick={() => {

                                    if (forList.length <= 1) {
                                        message.warning('至少保留一个优惠券')
                                        return
                                    }
                                    forList.splice(index, 1)
                                    setFunData([...forList])
                                }}
                            ></Icon>}

                        </Space>
                        {(index !== (forList.length - 1) && !editCouponStatus.status) && <Divider />}
                    </div>)
                })}
            </Modal>
        })()}

    </div>)
}
export default forwardRef(Coupon)